import java.util.HashMap;
import java.util.Stack;

/**
 * @projectName: com.xiayuanxing.designPattern
 * @className: Calculator
 * @author: xiayuanxing
 * @description: TODO
 * @date: 2022/1/17 16:19
 * @version: 1.0
 */
public class Calculator {

    //定义表达式
    private Expression expression;

    public Calculator(String expStr) {//expStr=a+b
        //安排运算先后顺序
        Stack<Expression> stack = new Stack<Expression>();
        //表达式拆分成字符数组
        char[] charArray = expStr.toCharArray();

        Expression left = null;
        Expression right = null;

        //遍历我们的字符数组，即遍历[a,+,b]
        //针对不同的情况，做处理
        for (int i = 0; i < charArray.length; i++) {
            switch (charArray[i]){
                case '+':
                    //从stack取出left=>"a"
                    left = stack.pop();
                    //取出右表达式"b"
                    right = new VarExpression(String.valueOf(charArray[++i]));
                    //然后根据得到left和right构建AddExpresson加入stack
                    stack.push(new AddExpression(left,right));
                    break;
                case '-':
                    //从stack取出left=>"a"
                    left = stack.pop();
                    //取出右表达式"b"
                    right = new VarExpression(String.valueOf(charArray[++i]));
                    //然后根据得到left和right构建AddExpresson加入stack
                    stack.push(new SubExpression(left,right));
                    break;
                default:
                    stack.push(new VarExpression(String.valueOf(charArray[i])));
                    break;
            }
        }
        //当遍历完整个charArray数组后，stack就得到最后Expression
        this.expression = stack.pop();
    }

    public int run(HashMap<String, Integer> var){
        //最后将表达式a+b和var={a=10,b=20}
        //然后传递给expression的interpreter进行解释执行
        return this.expression.interprete(var);
    }
}
